var setTimes = 10;
var initObj = {
    dom: '',
    actXnum:null,
    actYnum:null,
    header:[],
    data: [],
    count: [],
    cancelData: [],
    resumeData: [],
    copydata: [],
    isCtrlC: true,
    isdeaCate: false,//无数据时是否默认出现一行分部行
    chaNav: false,  //是否出现插入分部行按钮
    chaNavchild: false,//是否出现插入子分部行按钮
}

const flatten = function(data, level=1) {
    let result = [];
    if(!data){
        return result;
    }
    data.forEach(function(item, i, data){
        data[i].level = level;
        data[i].shou = data[i].shou || '';
        data[i].show = true;
        data[i].tdtype = 0;
        let childarr = item.children || [];
        // if(item.hasOwnProperty('children')){
        //     data[i].tdtype = 1;
        //     data[i].shou = 'down';
        // }
        if(item.iscate > 0){
            data[i].tdtype = 1;
            data[i].shou = 'down';
        }
        if (Array.isArray(childarr) && childarr.length > 0) {
            delete data[i].children;
            result.push(data[i])
            result=result.concat(flatten(childarr, level+1)) ;
        } else {
            result.push(data[i])
        }
    })
    return result;
};
const flattenHave = function(data, level=1) {
    let result = [];
    if(!data){
        return result;
    }
    data.forEach(function(item, i, data){
        data[i].level = level;
        let childarr = item.children || [];
        if (Array.isArray(childarr) && childarr.length > 0) {
            delete data[i].children;
            result.push(data[i])
            result=result.concat(flattenHave(childarr, level+1)) ;
        } else {
            result.push(data[i])
        }
    })
    return result;
};
function init(data) {

    initObj.dom = data.dom
    initObj.header = data.header
    initObj.data = flatten(data.data)
    initObj.count = data.count || []
    initObj.isdeaCate = data.isdeaCate || false
    initObj.chaNav = data.chaNav || false
    initObj.chaNavchild = data.chaNavchild || false


    for (var key in initObj.header){
        initObj.header[key].hide = initObj.header[key].hide ? initObj.header[key].hide : false;
        initObj.header[key].required = initObj.header[key].required ? initObj.header[key].required : false;
    }


    list_butt();
    list_header();
    list_list();
    drag_column();





    var budboxWidth = $(".budbox")[0].offsetWidth;
    var oneThWidth = (budboxWidth-50)/(initObj.header.length - 1)-1
    if(oneThWidth > 120){
        $("#"+initObj.dom+' thead tr th').css('width',oneThWidth+'px');
    }



    $("#"+initObj.dom+"_cancel").click(function () {
        cancelFunc();
    });
    $("#"+initObj.dom+"_resume").click(function () {
        resumeFunc();
    });
    $("#"+initObj.dom+"_copy_row").click(function () {
        butt_copy_row();
    });
    $("#"+initObj.dom+"_paste_row").click(function () {
        butt_paste_row();
    });
    $("#"+initObj.dom+"_top_row").click(function () {
        butt_top_row();
    });

    $("#"+initObj.dom+"_bottom_row").click(function () {
        butt_bottom_row();
    });
    $("#"+initObj.dom+"_del_row").click(function () {
        butt_del_row();
    });
    butt_delall_row();
    butt_open_close_column();
    butt_cha_row();
    butt_sets_column();
    $("#"+initObj.dom+"_nav_row").click(function () {
        butt_nav_row();
    });
    $("#"+initObj.dom+"_navchild_row").click(function () {
        butt_navchild_row();
    });
    $("#"+initObj.dom+"_list_row").click(function () {
        butt_list_row();
    });
    copyFunc();
    pasteFunc();
}


function list_butt() {

    var str = '';
    str += '<div id="budtable_cancel" class="chbut"><img src="/static/admin/images/main/cancel.png">撤销</div>';
    str += '<div id="budtable_resume" class="chbut"><img src="/static/admin/images/main/resume.png">恢复</div>';
    str += '<div id="budtable_copy_row" class="chbut"><img src="/static/admin/images/main/copy.png">复制行</div>';
    str += '<div id="budtable_paste_row" class="chbut"><img src="/static/admin/images/main/paste.png">粘贴行</div>';
    str += '<div id="budtable_cha_row" class="chbut"><img src="/static/admin/images/main/cha.png">插入行</div>';
    str += '<div id="chaDiv" class="layui-hide">';
    if(initObj.chaNav){
        str += '<div class="cols" id="budtable_nav_row">分部行</div>';
    }
    if(initObj.chaNavchild){
        str += '<div class="cols" id="budtable_navchild_row">子分部行</div>';
    }
    str += '<div class="cols" id="budtable_list_row">清单行</div>';
    str += '</div>';
    str += '<div id="budtable_top_row" class="chbut"><img src="/static/admin/images/main/top.png">上移</div>';
    str += '<div id="budtable_bottom_row" class="chbut"><img src="/static/admin/images/main/bottom.png">下移</div>';
    str += '<div id="budtable_del_row" class="chbut"><img src="/static/admin/images/main/del.png">删除行</div>';
    str += '<div id="budtable_delall_row" class="chbut"><img src="/static/admin/images/main/copy.png">删除全部</div>';
    str += '<div id="budtable_open_close_column" class="chbut"><img src="/static/admin/images/main/open.png">展开列</div>';
    str += '<div id="budtable_sets_column" class="chbut"><img src="/static/admin/images/main/sets.png">列设置</div>';
    $(".budopt").html(str);
}
function list_header() {
    var str = '<thead><tr>';
    for (var key in initObj.header){
        if(!initObj.header[key].hide){
            str += '<th>';
            if(initObj.header[key].required){
                str += '<text>*</text>';
            }
            str += initObj.header[key].title;
            str += '</th>';
        }
    }
    str += '</tr></thead>';
    $("#"+initObj.dom).html(str);
    list_nums(initObj.dom);
}


function listAddPar(data) {
    var lelarr = {};
    for(var mmm in data) {
        data[mmm]['zid'] = parseInt(mmm)+1;
        if(mmm == 0){
            data[mmm]['zidpar'] = 0;
            if(data[mmm].tdtype > 0){
                lelarr[1] = data[mmm]['zid'];
            }
        }else{
            var preLevel = data[parseInt(mmm)-1].level;
            var curLevel = data[mmm].level;

            if(curLevel == 1){
                data[mmm]['zidpar'] = 0;
                lelarr = {};
                lelarr[1] = data[mmm]['zid'];
            }else{
                if(curLevel < preLevel){
                    data[mmm]['zidpar'] = lelarr[parseInt(curLevel)-1];
                }
                if(curLevel == preLevel){
                    data[mmm]['zidpar'] = data[parseInt(mmm)-1]['zidpar'];
                }
                if(curLevel > preLevel){
                    data[mmm]['zidpar'] = data[parseInt(mmm)-1]['zid'];
                }

                if(data[mmm].tdtype > 0){
                    lelarr[data[mmm].level] = data[mmm]['zid'];
                }
            }
        }
    }
    return data;
}
function listToTree(list){
    var data = listAddPar(list);
    data.forEach(element => {
        let zidpar = element.zidpar;
        if(zidpar !== 0){
            data.forEach(ele => {
                if(ele.zid == zidpar){
                    if(!ele.children){
                        ele.children = [];
                    }
                    ele.children.push(element);
                }
            });
        }
    });
    data = data.filter(ele => ele.zidpar === 0);
    return data;
}




function list_list(iscancel=true, isresume=true) {
    $("#"+initObj.dom).children('tbody').remove();

    if(initObj.data.length < 1 && initObj.isdeaCate){
        initObj.data = flatten([{name:'',iscate:1}]);
    }

    for (var key in initObj.data){
        for (var mmm in initObj.header){
            let filed_type = initObj.header[mmm].type || '';
            let filed_field = initObj.header[mmm].field || '';
            let this_value = initObj.data[key][filed_field] || '';
            let field_default = initObj.header[mmm].default || null;
            let field_math = initObj.header[mmm].math || '';
            let field_mathduo = initObj.header[mmm].mathduo || '';


            if(!this_value){
                if(field_default !== null){
                    this_value = field_default;
                }
            }

            if(field_math){
                this_value = mathStrNumber(initObj.data[key][field_math] ? initObj.data[key][field_math] : '');
            }
            if(field_mathduo){
                this_value = mathStrFieldArr(field_mathduo, key)
            }

            if(filed_type == 'int'){
                this_value = parseInt(this_value) || 0;
            }
            if(filed_type == 'number'){
                this_value = mathRound(this_value || 0);
            }

            initObj.data[key][filed_field] = this_value
        }
    }

    if(initObj.count.length > 0){
        var treeData = updateTreeDataAdd(listToTree(initObj.data), initObj.count)
        initObj.data = flattenHave(treeData)

    }

    var str = '';
    var xmdanObj = [];
    var nums = 1;
    for (var key in initObj.data){
        if(initObj.data[key].show){
            var tdClss = 'lev'+initObj.data[key].level;

            var disabledClss = '';
            if(initObj.data[key].disabled || initObj.data[key].tdtype > 0){
                disabledClss = 'disabled'
            }
            str += '<tr class="containerTr" level="'+initObj.data[key].level+'" tdtype="'+initObj.data[key].tdtype+'" row="'+key+'" >';
            var iconshou = initObj.data[key].shou || '';

            for (var mmm in initObj.header){
                if(initObj.header[mmm].hide){
                    continue;
                }
                let filed_type = initObj.header[mmm].type || '';
                let filed_field = initObj.header[mmm].field || '';
                let this_value = initObj.data[key][filed_field] || '';
                let field_default = initObj.header[mmm].default || null;
                let field_disabled = initObj.header[mmm].disabled || false;

                var thisdisabledClss = '';
                if(field_disabled){
                    thisdisabledClss += ' disabled ';
                }

                var ActClass = '';
                if(initObj.actXnum == key && initObj.actYnum == mmm){
                    ActClass = ' active';
                }

                if(filed_type == 'numbers'){
                    // thisdisabledClss = ' disabled ';
                    str += '<td cell="'+mmm+'" class="'+ActClass+' '+filed_field+'">'+nums+'</td>';
                    nums++;
                }else if(filed_type == 'cate'){
                    str += '<td cell="'+mmm+'" class="'+tdClss+' '+' '+ActClass+' '+filed_field+'">';
                    if(initObj.data[key].tdtype > 0){
                        var shoutitle = '收起';
                        if(iconshou == 'right'){
                            shoutitle = '展开'
                        }
                        str += '<span><i class="layui-icon levicon layui-icon-'+iconshou+'" shou="'+iconshou+'" row="'+key+'" title="'+shoutitle+'"></i></span>';
                    }
                    str += '<span class="tdvv">'+this_value+'</span>';
                    str += '</td>';
                }else if(filed_type == 'xmdan'){
                    var danKey = parseInt(key)+1;
                    str += '<td cell="'+mmm+'" class="'+thisdisabledClss+disabledClss+ ActClass+' '+filed_field+'">';
                    str += '<div class="'+filed_field+danKey+'" key="'+danKey+'"></div>';
                    str += '</td>';
                    xmdanObj.push({dom: filed_field+danKey, data:initObj.header[mmm].xmdata, value:this_value, field:filed_field});
                }else if(filed_type == 'func'){
                    str += '<td cell="'+mmm+'" class="'+thisdisabledClss+disabledClss+ ActClass+' '+filed_field+'">';
                    if(initObj.header[mmm].callback){
                        str += initObj.header[mmm].callback(key, filed_field, this_value);
                    }
                    str += '</td>';
                }else if(filed_type == 'curjisuan'){
                    str += '<td cell="'+mmm+'" class="'+thisdisabledClss+disabledClss+ ActClass+' '+filed_field+'">';
                    if(initObj.header[mmm].callback){
                        str += initObj.header[mmm].callback(key, filed_field, this_value);
                    }
                    str += '</td>';
                }else{
                    if(disabledClss || thisdisabledClss){
                        str += '<td cell="'+mmm+'" class="'+thisdisabledClss+disabledClss+' '+ ActClass+' '+filed_field+'">'+this_value+'</td>';

                    }else{
                        str += '<td cell="'+mmm+'" class="'+' '+ ActClass+' '+filed_field+'">'+'<span class="tdvv">'+this_value+'</span>'+'</td>';
                    }

                }
            }
            str += '</tr>';
        }
    }

    $("#"+initObj.dom).append('<tbody class="container">'+str+'</tbody>')


    for (var key in xmdanObj){
        xmselect_list_dan(xmdanObj[key]['dom'], xmdanObj[key]['data'], xmdanObj[key]['value'], function (res) {
            var row = $("."+res.domname).parents('tr').attr('row') || 0;


            var xuanValue = '';
            if(res['arr'].length > 0){
                var xuanValue = res['arr'][0].value || '';
            }
            var newData = [];
            for (var aaa in initObj.data){
                if(aaa == row){
                    initObj.data[aaa][xmdanObj[key]['field']] = xuanValue
                }
                newData.push(initObj.data[aaa]);
            }
            initObj.data = newData;
            list_list();
        });
    }


    if(iscancel){
        if(initObj.cancelData.length > 19){
            initObj.cancelData.splice(0, 1);
        }
        initObj.cancelData.push(JSON.stringify(initObj.data))
    }

    if(isresume){
        initObj.resumeData = [];
    }

    setTimeout(function () {
        td_click();
        td_dbclick();
        td_levicon();
        ReWritable();
        cancelSet();
    },setTimes)
}
function list_list_children() {
    var str = '';
    var nums = 1;


    for (var key in initObj.data){
        if(initObj.data[key].show){
            var tdClss = 'lev'+initObj.data[key].level;

            var disadClss = '';
            if(initObj.data[key].disad){
                disadClss = 'disad'
            }
            str += '<tr class="containerTr" level="'+initObj.data[key].level+'" tdtype="'+initObj.data[key].tdtype+'" row="'+key+'" >';
            var iconshou = initObj.data[key].shou || '';


            for (var mmm in initObj.header){
                if(initObj.header[mmm].hide){
                    continue;
                }
                let filed_type = initObj.header[mmm].type || '';
                let filed_field = initObj.header[mmm].field || '';
                let this_value = initObj.data[key][filed_field] || '';

                var ActClass = '';
                if(initObj.actXnum == key && initObj.actYnum == mmm){
                    ActClass = ' active';
                }


                if(filed_type == 'numbers'){
                    str += '<td cell="'+mmm+'" class="'+disadClss+' '+ActClass+' '+filed_field+'">'+nums+'</td>';
                    nums++;
                }else if(filed_type == 'cate'){
                    str += '<td cell="'+mmm+'" class="'+tdClss+' '+disadClss+' '+ActClass+' '+filed_field+'">';
                    if(initObj.data[key].tdtype > 0){
                        var shoutitle = '收起';
                        if(iconshou == 'right'){
                            shoutitle = '展开'
                        }
                        str += '<span><i class="layui-icon levicon layui-icon-'+iconshou+'" shou="'+iconshou+'" row="'+key+'" title="'+shoutitle+'"></i></span>';
                    }
                    str += '<span class="tdvv">'+this_value+'</span>';
                    str += '</td>';
                }else if(filed_type == 'xmdan'){
                    str += '<td cell="'+mmm+'" class="'+disadClss+' '+ ActClass+' '+filed_field+'">';
                    str += '<div class="'+filed_field+nums+'" key="'+nums+'"></div>';
                    str += '</td>';
                }else{
                    str += '<td cell="'+mmm+'" class="'+disadClss+' '+ ActClass+' '+filed_field+'">'+'<span class="tdvv">'+this_value+'</span>'+'</td>';
                }
            }
            str += '</tr>';
        }
    }
    return str;
}



function td_click() {
    $("#"+initObj.dom+' td').on('click',function () {
        $("#"+initObj.dom+' tr').removeClass('activetr');
        $("#"+initObj.dom+' td').removeClass('active');
        $(this).addClass('active');
        initObj.actXnum = $(this).parents('tr').attr('row');
        initObj.actYnum = $(this).index();

        var cellindex = $(this).index();
        if(cellindex == 0){
            $(this).parents('tr').addClass('activetr');
        }
    });
}
function td_dbclick() {
    $("#"+initObj.dom+' td').on('dbclick',function () {
        // $("#"+initObj.dom+' td').removeClass('active');
        // $(this).addClass('active');
    });
}
function td_levicon() {
    $("#"+initObj.dom+' .levicon').click(function () {

        var newData = JSON.parse(JSON.stringify(initObj.data));

        var shou = $(this).attr('shou');
        var level = $(this).parents('tr').attr('level');
        var row = parseInt($(this).attr('row'));

        if(shou == 'down'){
            newData[row].shou = 'right';
        }else{
            newData[row].shou = 'down';
        }

        var fangRes = true;
        for (var key in newData){
            if(key > row){
                if(newData[key].level > level && fangRes){
                    if(shou == 'down'){
                        newData[key].show = false;
                        newData[key].shou = 'right';
                    }else{
                        newData[key].show = true;
                        newData[key].shou = 'down';
                    }
                }else{
                    fangRes = false;
                }
            }
        }
        initObj.data = newData;
        list_list();
    });
}

function list_nums() {
    setTimeout(function () {
        $.each($("#"+initObj.dom).children('tbody').children('tr'),function (key,val) {
            $(this).children('td:first-child').html(key+1);
        });
    },setTimes)
}
function drag_column() {
    var budboxWidth = $(".budbox")[0].offsetWidth;
    //用来存储当前更改宽度的Table Cell,避免快速移动鼠标的问题
    var tTD;
    var table = document.getElementById(initObj.dom);
    for (j = 0; j < table.rows[0].cells.length; j++) {
        table.rows[0].cells[j].onmousedown = function () {
            //记录单元格
            tTD = this;
            if (event.offsetX > tTD.offsetWidth - 10) {
                tTD.mouseDown = true;
                tTD.oldX = event.x;
                tTD.oldWidth = tTD.offsetWidth;
            }
            // 记录Table宽度
            table = tTD; while (table.tagName != 'TABLE') table = table.parentElement;
            tTD.tableWidth = table.offsetWidth;
        };
        table.rows[0].cells[j].onmouseup = function () {
            //结束宽度调整
            if (tTD == undefined) tTD = this;
            tTD.mouseDown = false;
            tTD.style.cursor = 'default';
        };
        table.rows[0].cells[j].onmousemove = function () {
            //更改鼠标样式
            if (event.offsetX > this.offsetWidth - 10)
                this.style.cursor = 'col-resize';
            else
                this.style.cursor = 'default';
            //取出暂存的Table Cell
            if (tTD == undefined) tTD = this;


            //调整宽度
            if (tTD.mouseDown != null && tTD.mouseDown == true) {
                tTD.style.cursor = 'default';
                if (tTD.oldWidth + (event.x - tTD.oldX)>0)
                    tTD.width = tTD.oldWidth + (event.x - tTD.oldX);
                //调整列宽
                tTD.style.width = tTD.width;
                tTD.style.cursor = 'col-resize';
                //调整该列中的每个Cell
                table = tTD; while (table.tagName != 'TABLE') table = table.parentElement;
                tTD.width = tTD.width < 80 ? 80 : tTD.width;
                for (j = 0; j < table.rows.length; j++) {
                    if(j==0){
                        table.rows[j].cells[tTD.cellIndex].style="width:"+tTD.width+"px;cursor:col-resize"
                    }else{
                        table.rows[j].cells[tTD.cellIndex].style="width:"+tTD.width+"px"
                    }
                    // table.rows[j].cells[tTD.cellIndex].width = tTD.width;
                }
                //调整整个表
                table.width = tTD.tableWidth + (tTD.offsetWidth-tTD.oldWidth);
                if(table.width < budboxWidth){
                    $("#"+initObj.dom).removeClass('tablewid').addClass('tablewidauto')
                    // $("#"+initObj.dom).css('width','auto');
                }else{
                    // $("#"+initObj.dom).css('width','100%');
                    $("#"+initObj.dom).addClass('tablewid').removeClass('tablewidauto')
                }
            }
        };
    }
    var _DOC = $(document);
    _DOC.on('mousedown', function(e){
        tTD = null;
    })
    _DOC.on('mouseup', function(e){
        tTD = null;
    })

}
function butt_copy_row() {
    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择要复制的清单数据");return false;
    }

    let tdtype = actObj.attr('tdtype') || 0;
    if(tdtype > 0){
        facade.error("只能复制清单行");return false;
    }
    var copyIndex = actObj.attr('row');
    initObj.copydata = JSON.parse(JSON.stringify(initObj.data[copyIndex]));
}
function butt_paste_row() {
    if(!initObj.copydata){
        facade.error("请先复制要粘贴的清单数据");return false;
    }
    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    var tdtype = actObj.attr('tdtype') || 0;
    var level = actObj.attr('level');
    var row = actObj.attr('row');
    if(row < 0){
        facade.error("请选择粘贴位置！");return false;
    }

    var nexttdtype = 0;
    if(row+1 < initObj.data.length){
        nexttdtype = initObj.data[row+1].tdtype || 0;
    }
    var newrow = row;
    var newLevel = level;

    if(tdtype > 0){
        newLevel = parseInt(level)+1;
        if( nexttdtype > 0 && initObj.data[row+1].level > level){
            facade.error("粘贴行位置下有子分部行，不能粘贴！");return false;
        }else{
            for (var key in initObj.data){
                if(key > row){
                    if(initObj.data[key].level > level){
                        newrow = key;
                    }else{
                        break;
                    }
                }
            }

        }
    }

    var thisCopyData = JSON.parse(JSON.stringify(initObj.copydata));

    var newData = [];
    for (var key in initObj.data){
        newData.push(initObj.data[key]);
        if(key == newrow){
            thisCopyData.level = newLevel;
            thisCopyData.shou = '';
            thisCopyData.show = 'true';
            newData.push(thisCopyData);
        }
    }
    initObj.data = newData;
    list_list();
}
function butt_top_row() {
    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择移动行！");return false;
    }

    var row = parseInt(actObj.attr('row') || 0);
    if(row == 0) return;


    var level = actObj.attr('level');
    var prevtlevel = initObj.data[row-1].level;

    var tdtype = actObj.attr('tdtype') || 0;
    var prevtdtype = initObj.data[row-1].tdtype || 0;

    if(tdtype > 0){
        if(prevtdtype > 0){
            if(prevtlevel < level){
                return;
            }else{
                var mysonStart=row,mysonEnd=row;
                for (key in initObj.data){
                    if(parseInt(key) > parseInt(row)){
                        if(initObj.data[key].level > level){
                            mysonEnd = key;
                        }else{
                            break;
                        }
                    }
                }

                var huanStart=row-1,huanEnd = row-1;
                if(prevtlevel > level){
                    for (iii=initObj.data.length-1; iii>=0; iii--){
                        if(iii < row){
                            if(initObj.data[iii].tdtype > 0 && initObj.data[iii].level == level){
                                huanStart = iii;
                                break;
                            }
                        }
                    }
                }


                var newData = [];
                for (kkk in initObj.data){
                    if(kkk == huanStart){
                        for (aaa in initObj.data){
                            if(parseInt(aaa) >= parseInt(mysonStart) && parseInt(aaa) <= parseInt(mysonEnd)){
                                newData.push(initObj.data[aaa])
                            }
                        }
                    }
                    if(parseInt(kkk) < parseInt(mysonStart) || parseInt(kkk) > parseInt(mysonEnd)){
                        newData.push(initObj.data[kkk])
                    }
                }

                initObj.actXnum = huanStart;
                initObj.data = newData;
            }
        }else{
            var mysonStart=row,mysonEnd= row;
            for (key in initObj.data){
                if(parseInt(key) > parseInt(row)){
                    if(initObj.data[key].level > level){
                        mysonEnd = key;
                    }else{
                        break;
                    }
                }
            }

            var huanStart,huanEnd = row-1;
            for (iii=initObj.data.length-1; iii>=0; iii--){
                if(iii < row){
                    if(initObj.data[iii].tdtype > 0 && initObj.data[iii].level == level){
                        huanStart = iii;
                        break;
                    }
                }
            }

            var newData = [];
            for (kkk in initObj.data){
                if(kkk == huanStart){
                    for (aaa in initObj.data){
                        if(parseInt(aaa) >= parseInt(mysonStart) && parseInt(aaa) <= parseInt(mysonEnd)){
                            newData.push(initObj.data[aaa])
                        }
                    }
                }
                if(parseInt(kkk) < parseInt(mysonStart) || parseInt(kkk) > parseInt(mysonEnd)){
                    newData.push(initObj.data[kkk])
                }
            }

            initObj.actXnum = huanStart;
            initObj.data = newData;

        }
    }else{
        if(prevtdtype > 0){
            return;
        }else{
            var rowData,rowTopData;
            rowData = initObj.data[row-1];
            rowTopData = initObj.data[row];
            initObj.data[row] = rowData;
            initObj.data[row-1] = rowTopData;
            initObj.actXnum = row-1;
        }
    }

    list_list();
}
function butt_bottom_row() {
    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择移动行！");return false;
    }

    var row = parseInt(actObj.attr('row') || 0);
    if(row == initObj.data.length-1) return;

    var level = parseInt(actObj.attr('level') || 0);
    var nexttlevel = initObj.data[row+1].level;

    var tdtype = actObj.attr('tdtype') || 0;
    var nexttdtype = initObj.data[row+1].tdtype || 0;

    if(tdtype > 0){
        if(nexttdtype > 0){
            if(nexttlevel < level){
                return;
            }else{
                var mysonStart=row,mysonEnd=row;
                for (key in initObj.data){
                    if(parseInt(key) > parseInt(row)){
                        if(initObj.data[key].level > level){
                            mysonEnd = key;
                        }else{
                            break;
                        }
                    }
                }

                var huanStart=parseInt(mysonEnd)+1,huanEnd = parseInt(mysonEnd)+1;
                if(huanStart > initObj.data.length-1){
                    return;
                }
                for (key in initObj.data){
                    if(parseInt(key) > parseInt(huanStart)){
                        if(initObj.data[key].level > initObj.data[huanStart].level){
                            huanEnd = key;
                        }else{
                            break;
                        }
                    }
                }


                var newData = [];
                for (kkk in initObj.data){
                    if(kkk == mysonStart){
                        for (aaa in initObj.data){
                            if(parseInt(aaa) >= parseInt(huanStart) && parseInt(aaa) <= parseInt(huanEnd)){
                                newData.push(initObj.data[aaa])
                            }
                        }
                        for (bbb in initObj.data){
                            if(parseInt(bbb) >= parseInt(mysonStart) && parseInt(bbb) <= parseInt(mysonEnd)){
                                newData.push(initObj.data[bbb])
                            }
                        }
                    }
                    if(parseInt(kkk) < parseInt(mysonStart) || parseInt(kkk) > parseInt(huanEnd)){
                        newData.push(initObj.data[kkk])
                    }
                }

                initObj.actXnum = huanEnd-huanStart+mysonStart+1;
                initObj.data = newData;
            }
        }else{
            var mysonStart=row,mysonEnd= row;
            for (key in initObj.data){
                if(parseInt(key) > parseInt(row)){
                    if(initObj.data[key].level > level){
                        mysonEnd = key;
                    }else{
                        break;
                    }
                }
            }

            var huanStart=parseInt(mysonEnd)+1,huanEnd = parseInt(mysonEnd)+1;
            if(huanStart > initObj.data.length-1){
                return;
            }
            for (key in initObj.data){
                if(parseInt(key) > parseInt(huanStart)){
                    if(initObj.data[key].level > initObj.data[huanStart].level){
                        huanEnd = key;
                    }else{
                        break;
                    }
                }
            }

            if(initObj.data[huanStart].level < initObj.data[mysonStart].level){
                return;
            }

            var newData = [];
            for (kkk in initObj.data){
                if(kkk == mysonStart){
                    for (aaa in initObj.data){
                        if(parseInt(aaa) >= parseInt(huanStart) && parseInt(aaa) <= parseInt(huanEnd)){
                            newData.push(initObj.data[aaa])
                        }
                    }
                    for (bbb in initObj.data){
                        if(parseInt(bbb) >= parseInt(mysonStart) && parseInt(bbb) <= parseInt(mysonEnd)){
                            newData.push(initObj.data[bbb])
                        }
                    }
                }
                if(parseInt(kkk) < parseInt(mysonStart) || parseInt(kkk) > parseInt(huanEnd)){
                    newData.push(initObj.data[kkk])
                }
            }

            initObj.actXnum = huanEnd-huanStart+mysonStart+1;
            initObj.data = newData;
        }
    }else{
        if(nexttdtype > 0){
            return;
        }else{

            var rowData,rowBotData;
            rowData = initObj.data[row+1];
            rowBotData = initObj.data[row];
            initObj.data[row] = rowData;
            initObj.data[row+1] = rowBotData;
            initObj.actXnum = row+1;
        }
    }

    list_list();
}
function butt_del_row() {

    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择要删除的数据！");return false;
    }
    layer.confirm('确定要删除吗？',function(index){
        var row = actObj.index();
        var level = actObj.attr('level');
        var fangRes = true;

        for (var key in initObj.data){
            if(key == row){
                delete initObj.data[key]
            }
            if(key > row){
                if(initObj.data[key].level > level && fangRes){
                    delete initObj.data[key]
                }else{
                    fangRes = false;
                }
            }
        }

        var newData = [];
        for (var key in initObj.data){
            newData.push(initObj.data[key]);
        }

        initObj.data = newData;
        list_list();
        layer.close(index);
    });
}
function butt_delall_row() {
    $("#"+initObj.dom+"_delall_row").click(function () {
        layer.confirm('确定要删除全部数据吗？',function(index){
            initObj.data = [];
            list_list();
            layer.close(index);
        });
    });
}
function butt_open_close_column() {
    $("#"+initObj.dom+"_open_close_column").click(function () {
        var openkey = parseInt($("#"+initObj.dom).attr('openkey') || 0);
        if(openkey > 0){
            $("#"+initObj.dom).addClass('tablewid').removeClass('tablewidauto');
            $("#"+initObj.dom).attr('openkey', 0);
            $(".budbox table tbody tr td").css('white-space','nowrap')
            $(this).html('<img src="/static/admin/images/main/open.png">展开列');
        }else{
            $("#"+initObj.dom).removeClass('tablewid').addClass('tablewidauto');
            $("#"+initObj.dom).attr('openkey', 1);
            $(".budbox table tbody tr td").css('white-space','pre')
            $(this).html('<img src="/static/admin/images/main/close.png">收起列');
        }
    });
}
function butt_cha_row() {
    $("#"+initObj.dom+"_cha_row").click(function (event) {
        var event = event || window.event;
        var pageY = event.pageY+10;
        var pageX = event.pageX;

        $("#chaDiv").css('top',pageY+'px');
        $("#chaDiv").css('left',pageX+'px');
        $("#chaDiv").removeClass('layui-hide');

        $(document).click(function () {
            $("#chaDiv").addClass('layui-hide');
        });

        $("#chaDiv").click(function (e) {
            e.stopPropagation();
        });

        event.stopPropagation();
        return false;
    });
}
function butt_sets_column() {
    $("#"+initObj.dom+"_sets_column").click(function (event) {
        $("#columnDiv").remove();
        var event = event || window.event;
        var pageY = event.pageY+10;
        var pageX = event.pageX;

        var str = '<div id="columnDiv" style="top: '+pageY+'px;left:'+pageX+'px">';
        for (var key in initObj.header) {
            str += '<div class="cols" num="'+key+'">';
            if(initObj.header[key].type == 'numbers' || initObj.header[key].type == 'cate'){
                initObj.header[key].hide = false;
            }
            if(initObj.header[key].hide){
                str += '<input type="checkbox" class="chbox">';
            }else{
                if(initObj.header[key].type == 'numbers' || initObj.header[key].type == 'cate'){
                    str += '<input type="checkbox" class="chbox" checked disabled>';
                }else{
                    str += '<input type="checkbox" class="chbox" checked>';
                }
            }
            str += initObj.header[key].title;
            str += '</div>';
        }
        str += '</div>';

        $(".budbox").append(str);



        $("#columnDiv .cols").click(function (e) {
            var num = parseInt($(this).attr('num'));
            var xuanObj = initObj.header[num];
            var colType = initObj.header[num].type ? initObj.header[num].type : '';
            var colhide = initObj.header[num].hide;
            if(colType == 'numbers' || colType == 'cate'){
                $(this).find('.chbox').prop('checked', true);return;
            }else{
                if(colhide){
                    initObj.header[num].hide = false;
                    $(this).find('.chbox').prop('checked', true);
                }else{
                    initObj.header[num].hide = true;
                    $(this).find('.chbox').prop('checked', false);
                }
                list_header();
                list_list();
            }


            var budboxWidth = $(".budbox")[0].offsetWidth-2;
            var tabWidth = $("#"+initObj.dom)[0].offsetWidth;

            if(tabWidth <= budboxWidth){
                $("#"+initObj.dom).removeClass('tablewid').addClass('tablewidauto')
                // $("#"+initObj.dom).css('width','auto');
            }else{
                // $("#"+initObj.dom).css('width','100%');
                $("#"+initObj.dom).addClass('tablewid').removeClass('tablewidauto')
            }

        });

        $(document).click(function () {
            $("#columnDiv").remove();
        });

        $("#columnDiv").click(function (e) {
            e.stopPropagation();//阻止事件向上冒泡
        });

        event.stopPropagation();
        return false;
    });
}



function butt_nav_row() {
    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择插入位置！");return false;
    }
    var row = parseInt(actObj.attr('row') || 0);
    var level = parseInt(actObj.attr('level') || 0);
    var tdtype = actObj.attr('tdtype') || 0;

    var deainfo = getDeaRowInfo(level, 'down',1)
    deainfo.iscate = 1;

    if(tdtype > 0){
        var mysonStart=row,mysonEnd=row;
        for (key in initObj.data){
            if(parseInt(key) > parseInt(row)){
                if(initObj.data[key].level > level){
                    mysonEnd = key;
                }else{
                    break;
                }
            }
        }

        var newData = [];
        for (kkk in initObj.data){
            newData.push(initObj.data[kkk])
            if(kkk == mysonEnd){
                newData.push(deainfo)
            }
        }
        initObj.data = newData;
    }else{
        facade.error("所选行不能插入分部行！");return false;
    }
    list_list();
}
function butt_navchild_row() {
    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择插入位置！");return false;
    }
    var row = parseInt(actObj.attr('row') || 0);
    var level = parseInt(actObj.attr('level') || 0);
    var tdtype = actObj.attr('tdtype') || 0;

    var deainfo = getDeaRowInfo(parseInt(level)+1, 'down',1)
    deainfo.iscate = 1;
    if(tdtype > 0){
        var mysonStart=row,mysonEnd=row;
        for (key in initObj.data){
            if(parseInt(key) > parseInt(row)){
                if(initObj.data[key].level > level){
                    mysonEnd = key;
                }else{
                    break;
                }
            }
        }

        var newData = [];
        for (kkk in initObj.data){
            newData.push(initObj.data[kkk])
            if(kkk == mysonEnd){
                newData.push(deainfo)
            }
        }
        initObj.data = newData;
        list_list(true, true);
        return false;
    }else{
        facade.error("所选行不能插入子分部行！");return false;
    }
}
function butt_list_row() {
    if(initObj.data.length < 1){
        var newObj = {};
        for (var mmm in initObj.header){
            let filed_field = initObj.header[mmm].field || '';
            if(filed_field){
                newObj[filed_field] = '';
            }
        }

        var newData = flatten([newObj]);
        initObj.data = newData
        list_list();
        return false;
    }

    var actObj = $("#"+initObj.dom+' .active').parents('tr');
    if(!actObj.length){
        facade.error("请选择插入位置！");return false;
    }
    var row = parseInt(actObj.attr('row') || 0);
    var level = parseInt(actObj.attr('level') || 0);
    var tdtype = actObj.attr('tdtype') || 0;

    if(tdtype > 0) {
        if (row + 1 < initObj.data.length) {
            var nexttdtype = initObj.data[row + 1].tdtype || 0;
            var nexttlevel = initObj.data[row + 1].level;
            if (nexttdtype > 0 && nexttlevel > level) {
                facade.error("该分部行下有子分部行，不能插入！");
                return false;
            }
        }
        var deainfo = getDeaRowInfo(parseInt(level)+1)
    }else{
        var deainfo = getDeaRowInfo(level)
    }
    deainfo.iscate = 0


    if(tdtype > 0){
        var mysonStart=row,mysonEnd=row;
        for (key in initObj.data){
            if(parseInt(key) > parseInt(row)){
                if(initObj.data[key].level > level){
                    mysonEnd = key;
                }else{
                    break;
                }
            }
        }

        var newData = [];
        for (kkk in initObj.data){
            newData.push(initObj.data[kkk])
            if(kkk == mysonEnd){
                newData.push(deainfo)
            }
        }
        initObj.data = newData;
    }else{
        var newData = [];
        for (kkk in initObj.data){
            newData.push(initObj.data[kkk])
            if(kkk == row){
                newData.push(deainfo)
            }
        }
        initObj.data = newData;
    }
    list_list();
}



function ReWritable() {
    var tbmain=document.getElementById(initObj.dom);
    for(var i=1; i<=tbmain.rows.length-1; i++)
    {
        for(var j=0;j<tbmain.rows[i].cells.length;j++)
        {
            tbmain.rows[i].cells[j].ondblclick=TdDoubleClick;
            tbmain.rows[i].cells[j].oncontextmenu=TdContextMenu;
            tbmain.rows[i].cells[j].onmouseover=TdOnmouseOver;
            tbmain.rows[i].cells[j].onmouseout=TdOnmouseOut;
        }
    }
}
function TdDoubleClick() {
    var istdvv = $(this).find('.tdvv').length;
    if(!istdvv){
        return;
    }

    var tdcag=document.getElementById("tdcag");
    if(tdcag!=null)  return;
    tdtxt=Trim($(this).find('.tdvv').html());
    tdtxt = tdtxt.replaceAll('<br>','\n');

    let actObj = $("#"+initObj.dom+' .active');
    if(actObj.length > 0){
        actObj.css('white-space', 'pre');
        actObj.css('width', '300px');
    }

    var deaWidth = this.offsetWidth+'px';
    var deaHeight = (this.offsetHeight-4)+'px';

    // var str="<div id='tdcag'><input type='text' onblur='ChangeTdText();' id='txtId' value='"+tdtxt+"' style='width: 100%;'>";
    var str="<div id='tdcag' style='position: relative;left:0;top: 0;'>";
    str+="<textarea type='text' onblur='ChangeTdText();' id='txtId' style='width: "+deaWidth+";height: "+deaHeight+";left: -10px;position: relative;padding: 0!important;'>"+tdtxt+"</textarea>";
    str+="<input type='hidden' id='tdInitValue' value='"+tdtxt+"'>";
    str+="</div>";
    $(this).find('.tdvv').html(str);

    var textareaQuery = document.querySelector('textarea');
    textareaQuery.addEventListener('input', (e) => {
        textareaQuery.style.height = e.target.scrollHeight + 'px';
    });

    var textarea = document.getElementById('txtId');
    var end = textarea.value.length;

    textarea.setSelectionRange(end, end);
    textarea.focus();
    // var ctr=textarea.createTextRange();
    // ctr.collapse(false);
    // ctr.select();
}
function Trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
function ChangeTdText() {
    // return false;
    var txtId=document.getElementById("txtId");
    if(txtId==null)
    {
        return;
    }
    var tdid=document.getElementById("tdcag").parentNode;
    tdid.innerText=Trim(txtId.value);


    var cellindex = parseInt($(tdid).parents('td').attr('cell')) || 0;
    var row = parseInt($(tdid).parents('tr').attr('row') || 0);

    var newData = [];
    for (var mmm in initObj.data){
        if(mmm == row){
            for (var nnn in initObj.header){
                if(nnn == cellindex){
                    initObj.data[mmm][initObj.header[nnn].field] = tdid.innerText;
                }
            }
        }
        newData.push(initObj.data[mmm])
    }

    initObj.data = newData;
    list_list();
}
function TdContextMenu() {
    $("#"+initObj.dom+' td').removeClass('active');
    $(this).addClass('active');
    initObj.actXnum = $(this).parents('tr').attr('row');
    initObj.actYnum = $(this).index();

    $(".budbox #contextmenuDiv").remove();
    var conTextMenuObj = [
        {name:'插入分部行',func:'butt_nav_row'},
        {name:'插入子分部',func:'butt_navchild_row'},
        {name:'插入清单行',func:'butt_list_row'},
        {name:'复制行',func:'butt_copy_row'},
        {name:'粘贴行',func:'butt_paste_row'},
        {name:'删除行',func:'butt_del_row'},
        {name:'上移行',func:'butt_top_row'},
        {name:'下移行',func:'butt_bottom_row'},
    ];

    var boxHeight = parseInt(conTextMenuObj.length) * 31;

    var clTop = this.offsetTop;
    var tabscoHei = $('#'+initObj.dom).parents('.budbox').scrollTop();
    var tabHei = $('#'+initObj.dom).parents('.budbox').height();
    // var clLeft = this.offsetLeft
    var cha = boxHeight - tabHei + clTop -tabscoHei;
    if(cha > 0){
        clTop = clTop - cha -15;
    }


    var event = event || window.event;
    var pageY = event.pageY;
    var pageX = event.pageX;

    var clTop = this.offsetTop;
    var tabscoHei = $('#'+initObj.dom).parents('.budbox').scrollTop();
    var tabHei = $('#'+initObj.dom).parents('.budbox').height();
    var sheng = tabHei - (clTop -tabscoHei);
    var cha = boxHeight - tabHei + clTop -tabscoHei;
    if(cha > 0){
        pageY = pageY - cha -30;
    }


    var str = '<div id="contextmenuDiv" style="top: '+pageY+'px;left:'+pageX+'px"><ul>';
    for (var key in conTextMenuObj) {
        str += '<li onclick="'+conTextMenuObj[key].func+'()">'+conTextMenuObj[key].name+'</li>';
    }
    str += '</ul></div>';

    $(".budbox").append(str);

    $(document).click(function () {
        $("#contextmenuDiv").remove();
    });
    return false;
}
function TdOnmouseOver() {
    $(".budbox #futext").remove();
    var tdWidth = this.offsetWidth - 22;
    var textWidth = $(this).find('.tdvv').innerWidth();
    var tdValue = $(this).find('.tdvv').text();
    if(tdWidth < textWidth){
        var event = event || window.event;
        var pageY = event.pageY;
        var pageX = event.pageX;

        var str = '<div id="futext" style="top: '+pageY+'px;left:'+pageX+'px">'+tdValue+'</div>';
        $(".budbox").append(str);

        $(document).click(function () {
            $("#contextmenuDiv").remove();
        });
    }
    return false;
}
function TdOnmouseOut() {
    $(".budbox #futext").remove();
    return false;
}

function copyFunc() {
    document.addEventListener('copy',function(e){
        if(e.target.nodeName == 'TEXTAREA'){
            return;
        }
        if(initObj.isCtrlC){
            let content;
            let actObj = $("#"+initObj.dom+' .active');
            if(actObj.length > 0){
                content = actObj.find('.tdvv').text();
            }
            initObj.isCtrlC = false;
            const ele = document.createElement('input')
            ele.setAttribute('value', content)
            document.body.appendChild(ele)
            ele.select()
            document.execCommand('copy')
            document.body.removeChild(ele)
            initObj.isCtrlC = true;
        }
        return false;
    })
}
function pasteFunc() {
    window.addEventListener("paste", function (e) {
        var actObj = $("#"+initObj.dom+' .active').parents('tr');
        if(actObj.length < 1){
            facade.error('请选择要插入的表格行');return false;
        }

        if (!(e.clipboardData && e.clipboardData.items)) {
            return;
        }

        var textarea = document.getElementById('txtId');
        if(textarea){
            return;
        }


        var html = e.clipboardData.getData('text/html');
        var $doc = new DOMParser().parseFromString(html,'text/html');
        if(html.search('Microsoft Excel') != -1){
            var ctrlArr = [];
            $( $doc.querySelectorAll('table tr') ).each(function () {
                var chilhang = [];
                $( $(this).children('td') ).each(function () {
                    chilhang.push($(this).text());
                });
                ctrlArr.push(chilhang)
            });


            var actObj = $("#"+initObj.dom+' .active').parents('tr');
            if(!actObj.length){
                facade.error("请选择粘贴位置！");return false;
            }
            var cellindex = parseInt($("#"+initObj.dom+' .active').index() || 0);
            var row = parseInt(actObj.attr('row') || 0);
            var level = parseInt(actObj.attr('level') || 0);
            var tdtype = actObj.attr('tdtype') || 0;


            if(tdtype > 0){
                if(row+1 < initObj.data.length){
                    var nexttdtype = initObj.data[row+1].tdtype || 0;
                    var nexttlevel = initObj.data[row+1].level;
                    if(nexttdtype > 0 && nexttlevel > level){
                        facade.error("该分部行下有子分部行，不能粘贴！");return false;
                    }
                }

                var mynewStart=row;
                for (key in initObj.data){
                    if(parseInt(key) > parseInt(row)){
                        if(initObj.data[key].level == (parseInt(level)+1) && initObj.data[key].tdtype == 0){
                            mynewStart = key;
                        }else{
                            break;
                        }
                    }
                }


                var fottData = [];
                for (key in initObj.data){
                    fottData.push(initObj.data[key]);
                    if(key == mynewStart){
                        fottData.push(getDeaRowInfo(parseInt(level)+1));
                    }
                }
                row = parseInt(mynewStart)+1;
                initObj.data = fottData;
                level += 1;
            }


            var newData = [];
            var startNums = 0;
            for (var key in initObj.data){
                if(key == row){
                    var xiangRes = true;
                    for (var mmm in ctrlArr){
                        var nextNum = parseInt(row)+parseInt(mmm);
                        if(nextNum < initObj.data.length && initObj.data[nextNum].tdtype == 0 && initObj.data[nextNum].level == level && xiangRes){
                            startNums = parseInt(nextNum)+1;
                            var deainfo = initObj.data[nextNum];
                        }else{
                            xiangRes = false;
                            var deainfo = getDeaRowInfo(level);
                        }


                        for (var aaa in ctrlArr[mmm]){
                            var xiacellindex = parseInt(cellindex) + 1 + parseInt(aaa);
                            var xiayigeObj = actObj.find('td:nth-child('+xiacellindex+')');
                            if(xiayigeObj.index() > 0){
                                var datacellindex = parseInt(xiayigeObj.attr('cell') || 0);
                                if(initObj.header[datacellindex] && initObj.header[datacellindex].field){
                                    deainfo[initObj.header[datacellindex].field] = ctrlArr[mmm][aaa] || '';
                                }
                            }
                        }
                        newData.push(deainfo);
                    }
                }else{
                    if(key >= startNums){
                        newData.push(initObj.data[key]);
                    }
                }
            }


            initObj.data = newData;
            list_list();
        }else{
            var content = e.clipboardData.getData("text") || '';
            let actObj = $("#"+initObj.dom+' .active');
            if(actObj.length > 0){
                actObj.find('.tdvv').html(content);

                var cellindex = parseInt(actObj.attr('cell') || 0);
                var row = parseInt(actObj.parents('tr').attr('row') || 0);

                initObj.data[row][initObj.header[cellindex].field] = content;
                list_list();
            }

        }
    })
}
function getDeaRowInfo(level=1,shou='',tdtype=0) {
    var deainfo = {shou:shou,level:level,show:true,tdtype:tdtype};
    if(tdtype > 0){
        deainfo.iscate = 1;
    }else{
        deainfo.iscate = 0;
    }
    for (var key in initObj.header){
        if(initObj.header[key].field){
            deainfo[initObj.header[key].field] = '';
        }
    }
    return deainfo;
}


function cancelSet() {
    // if(initObj.cancelData.length > 1){
    //     $("#"+initObj.dom+"_cancel").addClass('laytp-btn-success').removeClass('laytp-btn-grey')
    // }else{
    //     $("#"+initObj.dom+"_cancel").removeClass('laytp-btn-success').addClass('laytp-btn-grey')
    // }
}
function cancelFunc() {
    if(initObj.cancelData.length > 1){
        var poparr = initObj.cancelData.pop()
        initObj.resumeData.push(poparr);
        initObj.data = JSON.parse(initObj.cancelData[initObj.cancelData.length - 1]);
        list_list(false, false);
    }
}
function resumeFunc() {
    if(initObj.resumeData.length > 0){
        var poparr = initObj.resumeData.pop()
        initObj.data = JSON.parse(poparr);
        list_list(true, false);
    }
}


function mathStrFieldArr(str, rowkey) {
    var re = /\【[^\】]+\】/g
    var arr = str.match(re);

    var newData = {};
    for (var key in arr){
        var fname = arr[key].substring(1,arr[key].length-1)
        newData[fname] = parseFloat(initObj.data[rowkey][fname] || 0);
    }
    for (var mmm in newData){
        str = str.replace('【'+mmm+'】', newData[mmm])
    }
    return mathStrNumber(str);
}
function mathStrNumber(str, n=2) {
    if(!str){
        return 0;
    }
    if(str.substr(0,1) == '='){
        str = str.substr(1);
    }

    try {
        var resval = math.evaluate(str) || 0;
        return mathRound(resval, n);
    }catch (e) {
        return mathRound(0, n);
    }
}
function updateTreeDataAdd(treeData,fieldNameArray){
    for(var i=0;i<treeData.length;i++){
        if(treeData[i].children&&treeData[i].children.length>0){
            for(var k=0;k<fieldNameArray.length;k++){
                var fieldName = fieldNameArray[k];
                treeData[i].children = updateTreeDataAddChild(treeData[i].children,fieldName);
                var addSum = 0;

                for(var j=0;j<treeData[i].children.length;j++){
                    var childNum = treeData[i].children[j][fieldName];
                    addSum += parseFloat(childNum)
                }

                addSum = mathRound(addSum)

                treeData[i][fieldName] = addSum;
            }

        }else{
            for(var k=0;k<fieldNameArray.length;k++){
                var fieldName = fieldNameArray[k];
                if(!treeData[i][fieldName]){
                    treeData[i][fieldName] = addSum;
                }
            }

        }
        return treeData;
    }
}


function updateTreeDataAddChild(treeData,fieldName){
    for(var i=0;i<treeData.length;i++){
        if(treeData[i].children){
            treeData[i].children = updateTreeDataAddChild(treeData[i].children,fieldName);
            var addSum = 0;

            //循环相加计算和
            for(var j=0;j<treeData[i].children.length;j++){
                var childNum = treeData[i].children[j][fieldName];
                addSum += parseFloat(childNum)
            }
            addSum = mathRound(addSum)
            //赋值
            treeData[i][fieldName] = addSum;
        }else if(!treeData[i][fieldName]){
            treeData[i][fieldName] = 0;
        }
    }
    return treeData;
}
function mathRound(value, n=2) {
    var resval = Math.round(value * Math.pow(10, n)) / Math.pow(10, n) || 0;
    // return Number(resval).toFixed(n);
    return removeTrailingZeros(Number(resval).toFixed(n));
}


function getBudListData() {
    return JSON.parse(JSON.stringify(initObj.data));
}













